<!--用户管理-->
<template>
  <div class="page-container">
    <ex_super_table_page v-bind="option" ref="superTablePage" @selection-change="e => selection = e">
    </ex_super_table_page>

    <el-dialog :title="$tt('label_payment')" :visible.sync="dialogFormVisible" width="860px" height="250px"
      :close-on-click-modal="false">

      <el-form ref="rechargeFormEl" :model="payForm" :rules="rules" label-width="100px" class="common-form-panel-div"
        style="padding: 0px 10px; margin-top: 20px;">


        <el-row>
          <el-col>
            <el-form-item :label="$tt('label_payment_account')" prop="accountId">
              <label>{{ $enumShow(payForm.currencyType, 'CurrencyTypeEnum') + ' - ' + $enumShow(payForm.accountType,
                'CustomerAccountTypeEnum') }} </label>
              <!--              <el-select v-model="payForm.accountId" placeholder="请选择" style="width: 100%;">-->
              <!--                <el-option-->
              <!--                  v-for="item in customerAccountOptions"-->
              <!--                  :key="item.id"-->
              <!--                  :label="$enumShow(item.currencyType, 'CurrencyTypeEnum') + ' - ' + $enumShow(item.accountType, 'CustomerAccountTypeEnum')"-->
              <!--                  :value="item.id">-->
              <!--                </el-option>-->
              <!--              </el-select>-->

            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item :label="$tt('label_account_balance')">
              <el-input v-model="payForm.accountBalance" disabled>
                <template slot="append">{{ $enumShow(payForm.currencyType, 'CurrencyTypeEnum') }}</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item :label="$tt('label_payment_amount')">
              <el-input v-model="payForm.applyAmount" disabled>
                <template slot="append">{{ $enumShow(payForm.currencyType, 'CurrencyTypeEnum') }}</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="payForm.accountBalance < payForm.applyAmount">
          <el-col>
            <el-form-item label="">
              <label style="color:red;font-size:15px">
                {{ $tt('tip_advance_charge_account_balance_not_enough', {
                  amount: payForm.applyAmount -
                    payForm.accountBalance
                }) }}
              </label>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="payForm.refBillList && payForm.refBillList.length > 0">
          <label style="color:#81b1ff"> {{ $tt('label_bill_wait_pay_sum_amount') }}： {{ payForm.applyAmount }} </label>
        </el-row>
        <ex-table-auto class="el-table-nowwarp" ref="resourceDownloadGridPanelEl" :data="payForm.refBillList"
          autoFill="false" border v-if="payForm.refBillList && payForm.refBillList.length > 0">

          <el-table-column prop="billNo" :label="$tt('label_fms_subject_bill_number')" min-width="8">
            <template slot-scope="scope">
              {{ scope.row.billNo }}
            </template>
          </el-table-column>
          <el-table-column prop="waitPayAmount" :label="$tt('label_bill_wait_pay_amount')" min-width="8">
            <template slot-scope="scope">
              {{ scope.row.waitPayAmount }}
            </template>
          </el-table-column>
          <el-table-column prop="clientStatus" :label="$tt('label_status')" min-width="8">
            <template slot-scope="scope">
              {{ $enumShow(scope.row.clientStatus, 'FmsCustomerBillStatusEnum') }}
            </template>
          </el-table-column>
        </ex-table-auto>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $tt('label_cancel') }}</el-button>
        <el-button type="primary" @click="submitRechargeForm">{{ $tt('label_confirm') }}</el-button>
      </div>

    </el-dialog>
  </div>
</template>
<script>


export default {

  title: 'label_fms_bill_list_bill_manager',
  components: {},

  data() {

    let _this = this

    return {
      fileList: [],
      formModel: 'insert/update',
      dialogFormVisible: false,

      payForm: {
        accountId: '',
        accountName: '',
        accountBalance: 0, // 账户余额
        currencyType: '',
        applyAmount: 0, // 付款金额（账单汇总金额）
        refBillList: [],
      },

      rules: {
      },

      chooseRowId: -1,
      customerAccountOptions: []

    };
  },
  watch: {
    'dialogFormVisible'(val, old) {
      let _this = this
      if (val === false && old === true) {
        _this.payForm = {
          accountId: '',
          accountName: '',
          accountBalance: 0, // 账户余额
          currencyType: '',
          applyAmount: 0, // 付款金额
          refBillList: [],
          totalPayMoney: 0,
        }
      }
    }
  },
  created() {

    let _this = this

    _this.option = {
      search: {
        model: [
          { label: "label_fms_subject_bill_number", key: "billNo", attrs: { clearable: true } },
          { label: "label_fms_subject_bill_type", key: "productType", type: 'select', enum: 'PmsProductTypeEnum', attrs: { clearable: true } },
          {
            label: "label_status", key: "clientStatus", type: 'select', enum: 'FmsCustomerBillStatusEnum', attrs: { clearable: true }
          },

        ],
      },
      action: [
        {
          label: 'label_payment', click: this.prePayMoney
        },
        {
          label: 'label_batch_confirm', click: (row) => this.confirmBatch(this.selection)
        }
      ],

      table: {
        url: "/fms-api/client/FmsClientRpc/selectBill.json",
        // attrs: {
        //   'cell-style': ({row, column, rowIndex, columnIndex}) => {
        //     if (column.property == 'status') {
        //       return {color: row.status == 'NORMAL' ? this.$globalCss.successColor : this.$globalCss.infoColor}
        //     }
        //   }
        // },
        model: [
          { type: 'selection', clickToggle: true, },
          { key: 'billNo', label: 'label_fms_subject_bill_number', align: 'center' },
          {
            key: 'productType', label: 'label_fms_subject_bill_type', align: 'center',
            attrs: {
              formatter: (r, c, v, i) => {
                return this.$enumShow(v, 'PmsProductTypeEnum')
              }
            }
          },

          { key: 'billMonth', label: 'label_fms_subject_bill_period', align: 'center' },
          {
            key: 'happenTime', label: 'label_fms_bill_list_bill_date', width: 160, attrs: {
              formatter: (r, c, v, i) => {
                return this.$dateFormat(v)
              }
            }
          },
          { key: 'amount', label: 'label_fms_subject_bill_amount', align: 'center' },
          {
            key: 'currencyType', label: 'label_currency_kind',
            attrs: {
              formatter: (r, c, v, i) => {
                return this.$enumShow(v, 'CurrencyTypeEnum')
              }
            }
          },
          {
            key: 'clientStatus', label: 'label_status',
            width: 120,
            attrs: {
              formatter: (r, c, v, i) => {
                return this.$enumShow(v, 'FmsCustomerBillStatusEnum')
              }
            }
          },

          { key: 'payAmount', label: 'label_has_payment', align: 'center' },
          { key: 'waitPayAmount', label: 'label_wait_payment', align: 'center' },
          {
            type: 'operate', width: 220,
            operate: [
              {
                label: 'label_confirm', click: (row) => {
                  this.confirm(row)
                },
                if: (row) => {
                  return row.status === 'CUSTOMER_CONFIRM'
                },
              },
              {
                label: 'label_payment', click: (row) => { this.rowPay(row) },
                disabled: (row) => {
                  return row.status !== 'UNPAY'
                },
              }
            ],
          }
        ]
      }
    }

    _this.selectAccount()
  },

  props: {},
  destroyed() { },

  methods: {

    selectAccount() {

      let _this = this

      _this.$ajax({
        url: '/fms-api/client/FmsClientRpc/selectAccount.json',
        data: {
          'accountType': 'CASH',
          'status': 'ENABLE'
        },
        success: (res) => {
          if (res && res.data && res.data.rows) {
            _this.customerAccountOptions = res.data.rows
          } else {
            _this.customerAccountOptions = []
          }
        }
      });
    },
    confirmBatch(rows){

      if (rows) {

        let idList = []

        rows.forEach(row => {

          if (row.status !== 'CUSTOMER_CONFIRM') {
            this.$message.error(this.$tt("tip_bill_status_not_allow_confirm"))
            return
          }

          idList.push(row.id)
        });

        this.$ajax({
          url: "/fms-api/client/FmsClientRpc/auditBill.json",
          method: 'post',
          type: 'json',
          data: { idList: idList },
          success: (res) => {
            this.$message.success(this.$tt("tip_submit_success"))
            this.$refs['superTablePage'].reload()
          }
        })
      }
    },
    confirm(row) {
      var _this = this

      if (row.id) {
        _this.$ajax({
          url: "/fms-api/client/FmsClientRpc/auditBill.json",
          method: 'post',
          type: 'json',
          data: { idList: [row.id] },
          success: (res) => {
            _this.$message.success(_this.$tt("tip_submit_success"))
            _this.$refs['superTablePage'].reload()
          }
        })
      }
    },
    rowPay(row) {
      // 币种
      this.payForm.currencyType = row.currencyType
      this.$ajax({
        url: '/fms-api/client/FmsClientRpc/selectCurrencyAccount.json',
        data: {
          'currencyType': row.currencyType,
        },
        success: (res) => {
          if (res && res.data) {
            this.payForm.accountId = res.data.id
            this.payForm.accountType = res.data.accountType
            this.payForm.accountBalance = res.data.leftAmount
          } else {
            this.$message(
              this.$tt('tip_current_curreny_not_has_advance_charge_account', {
                currency: this.$enumShow(currency, 'CurrencyTypeEnum')
              })
            )
            return
          }
        }
      });

      let billNos = []
      billNos.push(row)

      this.payForm.refBillList = billNos
      this.payForm.applyAmount = row.waitPayAmount
      this.dialogFormVisible = true
    },
    prePayMoney() {
      let billNos = []
      let _list = this.selection

      // 前置校验
      if (_list === undefined || _list.length === 0) {
        return this.$message.error(this.$tt('tip_please_tick'))
      }
      let _currencyType = _list[0].currencyType
      for (var i = 0; i < _list.length; i++) {
        if (_list[i].status !== 'UNPAY') {
          return this.$message.error(this.$tt("tip_only_select_no_pay_bill_to_pay"))
        }
        if (_list[i].currencyType !== _currencyType) {
          return this.$message.error(this.$tt('tip_only_select_some_currency_bill_to_pay'))
        }
      }

      // 查询预付款账户
      this.$ajax({
        url: '/fms-api/client/FmsClientRpc/selectCurrencyAccount.json',
        data: {
          'currencyType': _currencyType,
        },
        success: (res) => {
          if (res && res.data) {
            this.payForm.accountId = res.data.id
            this.payForm.accountType = res.data.accountType
            this.payForm.accountBalance = res.data.leftAmount
          } else {
            this.$message(
              this.$tt('tip_current_curreny_not_has_advance_charge_account', {
                currency: this.$enumShow(currency, 'CurrencyTypeEnum')
              })
            )
            return
          }
        }
      });

      let money = 0
      for (var i = 0; i < _list.length; i++) {
        let _item = _list[i]
        billNos.push(_item)
        money += _item.waitPayAmount
      }
      this.payForm.currencyType = _currencyType
      this.payForm.applyAmount = money
      this.payForm.refBillList = billNos
      this.dialogFormVisible = true
    },

    submitRechargeForm() {

      let payBillList = []

      if (this.payForm.refBillList && this.payForm.refBillList.length > 0) {
        // 余额大于支付
        if (this.payForm.accountBalance > this.payForm.applyAmount) {
          this.payForm.refBillList.forEach((item) => {
            payBillList.push({
              billId: item.id,
              payAmount: item.waitPayAmount,
              accountId: this.payForm.accountId
            })
          })
          // 余额小于支付，拆分支付
        } else {
          let _balance = this.payForm.accountBalance
          this.payForm.refBillList.forEach((item) => {
            let _payAmount = 0
            if (_balance > 0) {
              if (_balance > item.waitPayAmount) {
                _payAmount = item.waitPayAmount
                _balance = _balance - item.waitPayAmount
              } else {
                _payAmount = _balance
                _balance = 0
              }
            }

            if (_payAmount > 0) {
              payBillList.push({
                billId: item.id,
                payAmount: _payAmount,
                accountId: this.payForm.accountId
              })
            }
          })
        }
      }

      if (payBillList && payBillList.length > 0) {
        this.$ajax({
          url: '/fms-api/client/FmsClientRpc/payBill.json',
          type: 'json',
          data: {
            'payBillObjList': payBillList
          },
          success: (res) => {
            if (res && res.code === 0) {
              this.$message({
                showClose: true,
                message: this.$tt('tip_submit_success'),
                type: 'success'
              })
              this.$refs['superTablePage'].reload()
              this.dialogFormVisible = false
            } else {
              this.$message.error(res.msg)
            }
          }
        });
      }
    }
  }
};

</script>
<style>
.small-btn span {
  font-size: 14px;
}

.small-btn .el-button--small span {
  font-size: 14px;
}
</style>
